package com.liujg.future.service;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.google.common.collect.Lists;
import com.liujg.future.config.MinioConfig;
import com.liujg.future.mapper.*;
import com.liujg.future.model.dto.PageDTO;
import com.liujg.future.model.entity.*;
import com.liujg.future.model.resp.Goods;
import com.liujg.future.model.resp.PageVO;
import com.liujg.future.util.MinioClientUtils;
import com.liujg.future.util.SingleHttpClient;
import com.mongodb.MongoWriteException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;

import static com.liujg.future.constant.ShopConstants.SHOP_BASE_URL;

/**
 * 店铺数据初始化
 */
@Service
@Slf4j
public class ShopInitializeService {

    @Autowired
    private ShopBannerRepository shopBannerRepository;

    @Autowired
    private ShopCategoryRepository shopCategoryRepository;

    @Autowired
    private ShopHotRepository shopHotRepository;

    @Autowired
    private ShopHotDetailRepository shopHotDetailRepository;
    @Autowired
    private ShopHotDetailGoodsRepository shopHotDetailGoodsRepository;

    @Autowired
    private ShopFreshGoodiesRepository shopFreshGoodiesRepository;

    @Autowired
    private ShopGuessLikeRepository shopGuessLikeRepository;
    @Autowired
    private ShopCategoryTopRepository shopCategoryTopRepository;

    @Autowired
    private ShopGoodsDetailRepository shopGoodsDetailRepository;

    @Autowired
    private MinioClientUtils minioClientUtils;

    @Autowired
    private MinioConfig minioConfig;
    private static final Long sleep = 300L;


    public void init() {

        bannerData();
        categoryData();
        hotData();
        freshGoodiesData();
        guessLikeData(new PageDTO(1, 20));
        categoryTopData();

        hotDetailData("/hot/preference", null, new PageDTO(1, 20));
        hotDetailData("/hot/inVogue", null, new PageDTO(1, 20));
        hotDetailData("/hot/oneStop", null, new PageDTO(1, 20));
        hotDetailData("/hot/new", null, new PageDTO(1, 20));
        log.info("-------------------init completed");
    }

    private void bannerData() {

        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }
        log.info("bannerData distributionSite {}", 1);
        Map<String, Object> params = new HashMap<>();
        params.put("distributionSite", 1);
        try {

            // 发送 GET 请求
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/home/banner", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                JSONArray result = data.getJSONArray("result");
                for (Object o : result) {
                    Banner banner = JSON.parseObject(JSON.toJSONString(o), Banner.class);
                    Optional<Banner> optional = shopBannerRepository.findById(banner.getId());
                    if (optional.isEmpty()) {
                        // distributionSite = 1 和2 数据一样
//                  banner.setDistributionSite(distributionSite);
                        // 处理图片
                        banner.setImgUrl(getFileAndUpload(banner.getImgUrl()));
                        // 保存到数据库
                        shopBannerRepository.insert(banner);
                    }
                }
            }

        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> bannerData");
        }

    }

    /**
     * 首页分类
     */
    private void categoryData() {
        log.info("categoryData");
        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }

        Map<String, Object> params = new HashMap<>();
        try {
            // 发送 GET 请求
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/home/category/mutli", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                JSONArray result = data.getJSONArray("result");
                for (Object o : result) {
                    Category category = JSON.parseObject(JSON.toJSONString(o), Category.class);
                    Optional<Category> optional = shopCategoryRepository.findById(category.getId());
                    if (optional.isEmpty()) {
                        // 处理图片
                        category.setIcon(getFileAndUpload(category.getIcon()));
                        // 保存到数据库
                        shopCategoryRepository.insert(category);
                    }
                }
            }
        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> categoryData");
        }
    }

    /**
     * 首页热门推荐
     */
    private void hotData() {
        log.info("hotData");
        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }
        Map<String, Object> params = new HashMap<>();
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/home/hot/mutli", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                JSONArray result = data.getJSONArray("result");
                for (Object o : result) {
                    Hot hot = JSON.parseObject(JSON.toJSONString(o), Hot.class);
                    Optional<Hot> optional = shopHotRepository.findById(hot.getId());
                    if (optional.isEmpty()) {
                        List<String> objects = Lists.newArrayList();
                        // 处理图片
                        for (String picture : hot.getPictures()) {
                            objects.add(getFileAndUpload(picture));
                        }
                        hot.setPictures(objects);
                        // 保存到数据库
                        shopHotRepository.insert(hot);
                    }
                }
            }

        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> hotData");
        }
    }

    /**
     * 新鲜好物
     */
    private void freshGoodiesData() {
        log.info("freshGoodiesData");
        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }
        Map<String, Object> params = new HashMap<>();
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/home/new", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                JSONArray result = data.getJSONArray("result");
                for (Object o : result) {
                    FreshGoodies freshGoodies = JSON.parseObject(JSON.toJSONString(o), FreshGoodies.class);
                    freshGoodies.setPicture(getFileAndUpload(freshGoodies.getPicture()));
                    // 保存到数据库
                    shopFreshGoodiesRepository.insert(freshGoodies);
                    goodsDetailData(freshGoodies.getId());
                }
            }
        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> freshGoodiesData");
        }

    }


    /**
     * 猜你喜欢
     */
    private void guessLikeData(PageDTO pageDTO) {
        log.info("guessLikeData page:{}",JSON.toJSONString(pageDTO));

        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("page", pageDTO.getPage());
        params.put("pageSize", pageDTO.getPageSize());
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/home/goods/guessLike", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                PageVO<GuessLike> result = data.getObject("result", new TypeReference<PageVO<GuessLike>>() {
                });

                for (GuessLike guessLike : result.getItems()) {
                    guessLike.setPicture(getFileAndUpload(guessLike.getPicture()));
                    // 保存到数据库
                    shopGuessLikeRepository.insert(guessLike);
                    goodsDetailData(guessLike.getId());
                }
                if (result.getPage() < result.getPages()) {
                    guessLikeData(new PageDTO(result.getPage() + 1, result.getPageSize()));
                }
            }
        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> guessLikeData: {}", JSON.toJSONString(pageDTO));
        }
    }

    /**
     * 热门推荐详情
     *
     * @param path /hot/preference 特惠推荐
     *             /hot/inVogue 爆款推荐
     *             /hot/oneStop 一站买全
     *             /hot/new 新鲜好物品
     */
    private void hotDetailData(String path, String subTypes, PageDTO pageDTO) {

        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("page", pageDTO.getPage());
        params.put("pageSize", pageDTO.getPageSize());
        params.put("subTypes", subTypes);
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, path, params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {

                HotDetail result = data.getObject("result", HotDetail.class);

                for (HotDetail.SubTypes subType : result.getSubTypes()) {

                    PageVO<HotDetailGoods> goodsItems = subType.getGoodsItems();
                    String subTypeId = subType.getId();
                    if (subTypes != null && !subTypeId.equals(subTypes)) {
                        continue;
                    }
                    log.info("path: {} subTypeId: {} page:{} pageSize:{} totalPage:{}", path, subType.getId(), subType.getGoodsItems().getPage(), subType.getGoodsItems().getPageSize(), subType.getGoodsItems().getPages());
                    for (HotDetailGoods item : goodsItems.getItems()) {
                        // 设置图片
                        item.setPicture(getFileAndUpload(item.getPicture()));
                        item.setSubTypeId(subType.getId());
                        // 设置主键id
                        item.setSubTypeIdGoodsId(subType.getId() + "_" + item.getId());
                        if(shopHotDetailGoodsRepository.findById(item.getSubTypeIdGoodsId()).isEmpty()){
                            shopHotDetailGoodsRepository.insert(item);
                        }
                        goodsDetailData(item.getId());
                    }

                    // 临时加 需要删除

                    if (goodsItems.getPage() < goodsItems.getPages()) {
                        // 不应该调用主方法 添加子方法
                        hotDetailData(path, subType.getId(), new PageDTO(goodsItems.getPage() + 1, goodsItems.getPageSize()));
                    }

                    subType.setGoodsItems(null);
                    // 重置页码
                    pageDTO.setPage(1);


                }

                if (!StringUtils.hasLength(subTypes)) {
                    result.setBannerPicture(getFileAndUpload(result.getBannerPicture()));
                    result.setPath(path);
                    if(shopHotDetailRepository.findById(result.getId()).isEmpty()){
                        shopHotDetailRepository.insert(result);
                    }

                }

            }
        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("hotDetailData exception error --------------> path {} subTypes {} pageDTO {}", path, subTypes, JSON.toJSONString(pageDTO));
        }
    }

    // 商品分类列表
    private void categoryTopData() {
        log.info("categoryTopData");
        try {
            Thread.sleep(sleep);
        } catch (Exception e) {
            log.error("执行失败");
        }

        Map<String, Object> params = new HashMap<>();
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/category/top", params);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                List<CategoryTop> result = data.getList("result", CategoryTop.class);
                for (CategoryTop categoryTop : result) {
                    // 图片转存
                    categoryTop.setPicture(getFileAndUpload(categoryTop.getPicture()));
                    List<String> pics = Lists.newArrayList();
                    for (String imageBanner : categoryTop.getImageBanners()) {
                        pics.add(getFileAndUpload(imageBanner));
                    }
                    categoryTop.setImageBanners(pics);

                    for (CategoryTop.CategoryChildren child : categoryTop.getChildren()) {
                        child.setPicture(getFileAndUpload(child.getPicture()));
                        List<Goods> goods = child.getGoods();
                        // 获取goods详情 图片转换
                        goods.forEach(goodsItem -> {
                            goodsItem.setPicture(getFileAndUpload(goodsItem.getPicture()));
                            goodsDetailData(goodsItem.getId());
                        });
                    }
                    shopCategoryTopRepository.insert(categoryTop);
                }

            }
        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> categoryTopData");
        }
    }

    // 商品详情
    private synchronized void goodsDetailData(String id) {

        // 查询数据库是否存在数据
        Optional<GoodsDetail> optionalGoodsDetail = shopGoodsDetailRepository.findById(id);
        if (optionalGoodsDetail.isPresent()) {
            log.info("goods_detail 商品信息以存在 id:{}", id);
            return;
        }
        /*try {
            Thread.sleep(sleep);
        }catch (Exception e){
            log.error("执行失败");
        }*/
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        try {
            String res = SingleHttpClient.get(SHOP_BASE_URL, "/goods", params);
            System.out.println("----------->" + id);
            JSONObject data = JSON.parseObject(res);
            if ("1".equals(data.getString("code"))) {
                GoodsDetail goodsDetail = data.getObject("result", GoodsDetail.class);
                // 图片处理
                List<String> pics = Lists.newArrayList();
                for (String imageBanner : goodsDetail.getMainPictures()) {
                    pics.add(getFileAndUpload(imageBanner));
                }
                goodsDetail.setMainPictures(pics);

                if (Objects.nonNull(goodsDetail.getBrand())) {
                    goodsDetail.getBrand().setPicture(getFileAndUpload(goodsDetail.getBrand().getPicture()));
                    goodsDetail.getBrand().setLogo(getFileAndUpload(goodsDetail.getBrand().getLogo()));
                }
                // specs picture
                if (!CollectionUtils.isEmpty(goodsDetail.getSpecs())) {
                    List<GoodsDetail.Spec> specs = goodsDetail.getSpecs();
                    for (GoodsDetail.Spec spec : specs) {
                        List<GoodsDetail.SpecValues> values = spec.getValues();
                        for (GoodsDetail.SpecValues value : values) {
                            value.setPicture(getFileAndUpload(value.getPicture()));
                        }
                    }
                }
                // sku picture
                if (!CollectionUtils.isEmpty(goodsDetail.getSkus())) {
                    List<GoodsDetail.Sku> skus = goodsDetail.getSkus();
                    for (GoodsDetail.Sku sku : skus) {
                        sku.setPicture(getFileAndUpload(sku.getPicture()));
                    }
                }
                // details pictures
                if (!CollectionUtils.isEmpty(goodsDetail.getDetails().getPictures())) {
                    List<String> detailsPictures = Lists.newArrayList();
                    List<String> detailsPics = goodsDetail.getDetails().getPictures();
                    for (String detailsPic : detailsPics) {
                        detailsPictures.add(getFileAndUpload(detailsPic));
                    }
                    goodsDetail.getDetails().setPictures(detailsPictures);
                }
                // similarProducts picture
                if (!CollectionUtils.isEmpty(goodsDetail.getSimilarProducts())) {
                    List<Goods> similarProducts = goodsDetail.getSimilarProducts();
                    for (Goods similarProduct : similarProducts) {
                        similarProduct.setPicture(getFileAndUpload(similarProduct.getPicture()));
                    }
                }
                // hotByDay picture
                if (!CollectionUtils.isEmpty(goodsDetail.getHotByDay())) {
                    List<Goods> hotByDay = goodsDetail.getHotByDay();
                    for (Goods hotByDayItem : hotByDay) {
                        hotByDayItem.setPicture(getFileAndUpload(hotByDayItem.getPicture()));
                    }
                }


                try {
                    log.info("goods_detail 商品信息入库成功 start id:{}", id);
                    shopGoodsDetailRepository.insert(goodsDetail);
                    log.info("goods_detail 商品信息入库成功 end id:{}", id);
                } catch (MongoWriteException e) {
                    log.error("MongoWriteException error --------------> goods_id: {}", id);
                }

            }

        } catch (URISyntaxException | IOException | InterruptedException e) {
            log.error("exception error --------------> goods_id: {}", id);
        }
    }

    private String getFileAndUpload(String urlStr) {

        try {
            if (!StringUtils.hasLength(urlStr)) {
                return null;
            }
            URL url = new URI(urlStr).toURL();
            // 获取协议、主机和路径 去掉url 参数
            String protocol = url.getProtocol();
            String host = url.getHost();
            String path = url.getPath();
            String baseUrl = protocol + "://" + host + path;

            String minioFileName = /*System.currentTimeMillis() +*/ FileUtil.getName(baseUrl);
            String fileName = FileUtil.getPrefix(baseUrl);
            String extName = FileUtil.extName(baseUrl);
            String contentType = "png".equals(extName) ? "image/png" : "image/jpeg";

            InputStream in = url.openStream();
            MultipartFile file = new MockMultipartFile(fileName, null, contentType, in);
            String bucketName = minioConfig.getBucketName();
            minioClientUtils.putObject(bucketName, file, minioFileName);
            return minioClientUtils.getObjectUrl(bucketName, minioFileName);

        } catch (Exception e) {
            log.error("上传失败 error ----> url: {}", urlStr);
            return null;
        }
    }
}
